var $activePage;
var $prevPage;
var $transition = "slide";
var $loadPageUrl;

/* set defaults */
var curHash = window.location.hash;
// remove hash for pages that have not yet loaded.
if ($(curHash).length == 0) 
	window.location.hash = "";

/* check for a change in hash (back or forward buttons) */
setInterval(function() {
	if (curHash != window.location.hash) {
  		curHash = window.location.hash;
  
  		if (curHash != "#dialog") {
  			closeDialog();
			if (curHash == "")
				curHash = "#home";
			loadPage($loadPageUrl, curHash.substr(1), $transition);
  		} 
 	}
}, 250);

$(function () {
	// set $activePage
	$('div[data-role="page"]:first').addClass('ui-page-active');
	$activePage = $('.ui-page-active');
	
	adjustHeight();
	
	// display email demo dialog event
	$('.ui-page-active .cta-buttons a, .email-link, .button-email-demo').live("click", function(e) {
		$button = $(this);

		$('.ui-page-active:last').after('<div id="wrapper"></div>');
		$('#wrapper').load($button.attr('href'), function(response, status, xhr) {
			if (status == "success") {
				success = true;
				loadDialog($('#wrapper div[data-role="dialog"]').attr('id'));
			}
		});
	
		return false;
	});
	
	// Prev and Next button clicks
	$('.ui-page-active .prev, .ui-page-active .next, .take-a-preview, .close-demo, .close-demo-red').live('click', function(event) {
		event.preventDefault();
		if ($('div').filter(":animated").length == 0) {
			$button = $(this);
			if ($button.attr('data-rel') == "dialog") {
				$('.ui-page-active:last').after('<div id="wrapper"></div>');
				$('#wrapper').load($button.attr('href'), function(response, status, xhr) {
					if (status == "success") {
						success = true;
						loadDialog($('#wrapper div[data-role="dialog"]').attr('id'));
					}
				});
			}
			else {
				$transition = $button.attr('data-transition');
				$loadPageUrl = $button.attr('href');
				window.location.hash = $button.attr('data-url');
			}
		}
		return false;
	});
	
	// Email Dialog submit handler
	$('.ui-page-active.ui-dialog #submit').live("click", function() {
        var formData = $("#callAjaxForm").serialize();

        $.ajax({
            type: "POST",
            url: "../email.php",
            cache: false,
            data: formData,
            success: onSuccess,
            error: onError
        });

        return false;
    });
    
    // click outside the dialog box to close the dialog
    $('.ui-dialog').live('click', function(event) {
    	if ($(this).attr('data-url') != "orientate") {
		    if (typeof(event.pageX) == 'number') {
		        var $content = $(this).find('div[data-role="content"] .gradient');
		        var $contentPos = $content.offset();
		        if (event.pageX > $contentPos.left && event.pageX < $contentPos.left + $content.width() &&
		            event.pageY > $contentPos.top && event.pageY < $contentPos.top + $content.height()) {
		            
		        }
		        else {
		            $('.ui-dialog').each(function() {
		                closeDialog();
		                $('.dialog-thanks').hide();
		                $('.dialog-form').show();
		            });
		        }
		    }
		}
	});
	// tapping outside the dialog box to close the dialog
	$('.ui-dialog').live('touchstart', function(event) {
		if ($(this).attr('data-url') != "orientate") {
			var pageX = event.originalEvent.touches[0].pageX;
			var pageY = event.originalEvent.touches[0].pageY;
		    if (typeof(pageX) == 'number') {
		        var $content = $(this).find('div[data-role="content"] .gradient');
		        var $contentPos = $content.offset();
		        if (pageX> $contentPos.left && pageX < $contentPos.left + $content.width() &&
		            pageY > $contentPos.top && pageY < $contentPos.top + $content.height()) {
		            
		        }
		        else {
		            $('.ui-dialog').each(function() {
		                closeDialog();
		                $('.dialog-thanks').hide();
		                $('.dialog-form').show();
		            });
		        }
		    }
		}
	});
	
	// Detect Orientation
	detectOrientation();
    $(window).resize(function () {
        detectOrientation();
    });
	
	setupGestures();
});

function loadDialog(dialogId) {
	if ($activePage.attr('id') != dialogId) {
		$prevPage = $('.ui-page-active');
		$('.ui-page-active').removeClass('ui-page-active').fadeTo('fast', 0.1);
		$('#'+dialogId).unwrap().addClass('ui-page ui-dialog ui-page-active').fadeIn('fast').css('z-index', 10);
		$activePage = $('.ui-page-active');
		window.location.hash = "dialog";
		$('body').height($(window).height()).css('min-height', $activePage.height());
	}
}

function loadPage(url, pageId, transition) {
	if ($activePage.attr('id') != pageId) {
		if ($('#'+pageId).length > 0) {
			$prevPage = $('.ui-page-active');
			$('.ui-page-active').removeClass('ui-page-active');
			$('#'+pageId).addClass('ui-page ui-page-active');
			$activePage = $('.ui-page-active');
			$('body').height($(window).height()).css('min-height', $activePage.height());
			windowWidth = $(window).width();
			
			if ($activePage.index() < $prevPage.index()) // reverse the direction
				transition += " reverse";
			
			// transitions
			$prevPage.css('z-index', 2);
			if (transition.indexOf("slide") > -1) {
				if (transition.indexOf("reverse") > -1) {
					$activePage.css({'z-index':1, 'left':-windowWidth, 'display':'block'}); 
					$prevPage.animate({'left':windowWidth, 'z-index': 1}, {duration:500, queue:false}, 'swing').promise().done(function() { $prevPage.hide();});
					$activePage.animate({'left':0, 'z-index':2}, {duration:500, queue:false}, 'swing').promise().done(function() {
						detectOrientation();
					});
				}
				else {
					$activePage.css({'z-index':1, 'left':windowWidth, 'display':'block'});
					$prevPage.animate({'left':-windowWidth, 'z-index':1}, {duration:500, queue:false}, 'swing').promise().done(function() { $prevPage.hide();});
					$activePage.animate({'left':0, 'z-index':2}, {duration:500, queue:false}, 'swing').promise().done(function() {
						detectOrientation();
					}); 
				}
			}
			else if (transition.indexOf("pop") > -1) {
				if (transition.indexOf("reverse") > -1) {
					$prevPage.animate({'width':0, 'height':0, 'display':'none', 'z-index':1, 'left':'50%'}, {duration:'fast', queue:false}, 'swing').promise().done(function() {
						$prevPage.hide();
						$activePage.css({'z-index':2, 'display':'block'}).promise().done(function() {
							detectOrientation();
						});
					});
				}
				else {
					$activePage.css({'z-index':1, 'width':0,'height':0, 'display':'block', 'left':'50%'}); 	// before state
					$prevPage.hide('500', function() {
						$(this).css({'z-index':1});
						$activePage.animate({'width':'100%', 'height':'100%', 'left':'0'}, {duration:'fast', queue:false}, 'swing').promise().done(function(){
							detectOrientation();
						});
					});
				}
			}
			
			// load the image
			if ($activePage.hasClass('demo')) {
				var industry = $activePage.find('.image').attr('data-industry');
				var slide = $activePage.find('.image').attr('data-image');
				url = '../img/tablet/demos/' + industry + '/' + slide;
				
				var demoImage = new Image();
				demoImage.onload = function() {
					$activePage.find('.image').css({'background-image' : 'url(' + url + ')'}).find('img').remove();
				}
				demoImage.src = url;
			}
		} 
		else {
			if (url != null) {
				$.ajax({
					type: "GET", 
					dataType: "html",
					url: url,
					success: function(data) {
						$pageToLoad = $(data).filter('div[data-role="page"]');
						$('div[data-role="page"]:last').after($pageToLoad);
						if ($('div[data-url="orientate"]').length == 0) {
							$potentialDialog = $(data).filter('div[data-url="orientate"]');
							$('div[data-role="page"]:last').after($potentialDialog);
						}
						loadPage(null, pageId, transition);
					}
				});
			}
		}
	}
}

function setupGestures() {
	$('body').touchwipe({
		wipeLeft: function() {
			if ($('div').filter(":animated").length == 0) {
				$('.next:visible').click();
			} 
		},
		wipeRight: function() {
			if ($('div').filter(":animated").length == 0) {
				$('.prev:visible').click();
			} 
		},
		min_move_x: 20,
		min_move_y: 20,
		preventDefaultEvents: false
	});
}

function detectOrientation() {
	if (window.innerHeight > window.innerWidth) {
		// portrait
        if ($activePage.hasClass('demo'))  {
        	loadDialog("popup");
        }
    }
    else {
    	// landscape
        if ($activePage.attr('data-url') == "orientate") {
        	closeDialog();	
        }
        // position the next and prev buttons
        var footerHeight = $(".ui-page-active #footer .copy").height();
        var topOffset = (window.innerHeight - footerHeight) / 2;
        $('.demo .next:visible').css('top', topOffset);
        $('.demo .prev:visible').css('top', topOffset);
        
        // position the demo images
        if (curHash.toLowerCase() == "#resourceinfo2" || curHash.toLowerCase() == "#resourceinfo4") {
        	$('.demo-image .image:visible').css({'background-size':'100% 100%', 'height':window.innerHeight - footerHeight + 10});
       		$('.iphone .demo-image .image:visible').css({'background-size':'100% 100%', 'height':window.innerHeight - footerHeight});
        }
        else if (curHash.toLowerCase() == "#governmentinfo1") {
        	$('.demo-image .image:visible').css({'background-size':'100% 100%', 'height':window.innerHeight - footerHeight + 10});
       		$('.iphone .demo-image .image:visible').css({'background-size':'100% 100%', 'height':window.innerHeight - footerHeight});
        }
        else {
	        $('.demo-image .image:visible').css({'background-size':'100% 100%', 'height':window.innerHeight - footerHeight + 10});
	       	$('.iphone .demo-image .image:visible').css({'background-size':'100% 100%', 'height':window.innerHeight - footerHeight});
       	}
    }
    
    adjustHeight();
}

function adjustHeight() {
	var minHeight = 10;
	$activePage.children().each(function() {
		minHeight += $(this).innerHeight();
	});
	
	if ($(window).height() > minHeight)
		minHeight = $(window).height();
	if ($('body').children().filter('.ui-page-active').hasClass('demo'))
	{
		$('body').scrollTop(0);
		minHeight = window.innerHeight;
	}
	$('body').height(minHeight).css('min-height', minHeight);
}

function onSuccess(data, status)
{
    $('.dialog-form').fadeOut(500).hide();
    $('.dialog-thanks').fadeIn(500).show();
    $('.ui-dialog .dialog-thanks .copy').vAlign();

}

function onError(data, status)
{
    // handle an error
}

function closeDialog() {
	if ($("#popup:visible, #iframe:visible").length > 0) {
		$("#popup, #iframe").removeClass('ui-page-active').fadeOut('fast').css('z-index', 1);
		if ($("#popup").attr('data-url') != "orientate") {
			$('#popup').remove();
		}
		$("iframe").remove();
		if ($prevPage != null ) {
			
			$activePage = $prevPage.addClass('ui-page-active').fadeTo('fast', 1);
			$prevPage = null;
		}
		var minHeight = $activePage.height();
		if ($(window).height() > $activePage.height())
			minHeight = $(window).height();
		$('body').height(minHeight).css('min-height', minHeight);

	}
}       

(function ($) {
    // VERTICALLY ALIGN FUNCTION
    $.fn.vAlign = function () {
        return this.each(function (i) {
            var ah = $(this).height();
            var ph = $(this).parent().height();
            var mh = Math.ceil((ph - ah) / 2);
            $(this).css('margin-top', mh);
        });
    };
})(jQuery);

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});